/**
 * xone 对于 crud 操作的混入
 */
export default {
  computed1: {
    /**
     * crud 类型，Craete:增 Delete:删 Update:改 List:查 Submit:通用提交
     */
    xcrudType() {
      return this.getXMeta('type', '', {xbase: 'xcrud'})
    },
    /**
     * 是否分页
     */
    xcrudCanPaging() {
      return this.getXMeta('canPaging', {xbase: 'xcrud'})
    },

    /**
     * crud 查到列表数据的数据路径
     */
    xcrudDataPathList() {
      return '._xcrudList'
    },
    /**
     * crud 查到列表数据的条目的数据路径
     */
     xcrudDataPathListItem() {
      return p=>'._xcrudList.'+p
    },
    /**
     * crud 查询顾虑数据的数据路径
     */
    xcrudDataPathQuery() {
      return '._xcrudQuery'
    },
    /**
     * crud 查询分页的数据路径
     */
    xcrudDataPathPaging() {
      return '._xcrudPaging'
    },
    /**
     * crud 详情，增加，修改，提交的数据路径
     */
    xcrudDataPathDetail() {
      return '._xcrudDetail'
    },
    /**
     * crud 父数据数据路径
     */
    xcrudDataPathParent() {
      return '._xcrudParent'
    },
    /**
     * crud 主 id 数据路径
     */
    xcrudDataPathId() {
      return '._xcrudId'
    },
  },
  methods: {
    /**
     * 页面的初始化或者下拉刷新处理
     */
    refresh() {
      let type = this.getXMeta('type', {xbase: 'xcrud'})

      if(type==='list') {
        setTimeout(()=>{
          this.setXCrudPaging('pageIndex', 1)
          return this.doList()
        }, 100)
      } if(type==='detail') {
        return this.doDetail()
      } else if(type==='update'&&this.getXMeta('updateByDetail', {xbase: 'xcrud'})) {
        return this.doDetail()
      }else {
        return Promise.resolve()
      }
    },
    /**
     * 页面的加载更多
     */
    more() {
      if(this.xcrudType!=='list'||(this.getXMeta('canPaging', {xbase: 'xcrud'})===false)) return Promise.resolve()
      let list = this.getXCrudList()
      let pagging = this.getXCrudPaging()
      if(list.length>=pagging.total) return Promise.resolve()
      this.setXCrudPaging('pageIndex', pagging.pageIndex+1) 
      return this.doList()
    },
    

    /**
     * crud 列表数据
     */
    getXCrudList(index) {
      let list = this.getXData(this.xcrudDataPathList, '', [])
      return index!==undefined?list[index]:list
    },
    setXCrudList(list) {
      this.setXData('', list, '._xcrudList')
      return list
    },
    /**
     * crud 过滤数据
     */
    getXCrudQuery(field) {
      return this.getXData(field, {xbase: '._xcrudQuery'})
    },
    setXCrudQuery(field, value, reset) {
      if(!field&&!reset) value = {...this.getXCrudDetail(), ...value}
      this.setXData(field, value, this.xcrudDataPathQuery)
      return value
    },
    /**
     * crud 查询分页数据
     */
    getXCrudPaging(field) {
      return this.getXData(field, {xbase: '._xcrudPaging'})
    },
    setXCrudPaging(field, value, reset) {
      if(!field&&!reset) value = {...this.getXCrudDetail(), ...value}
      this.setXData(field, value, this.xcrudDataPathPaging)
      return value
    },
    /**
     * crud 详情，增加，修改，提交的数据
     * 设置 crud 详情，增加，修改，提交的数据
     * field 如果为空设置整个详情，该方法可能导致大面积更新，性能很低， reset 为真，丢弃原数据
     */
    getXCrudDetail(field) {
      return this.getXData(field, {xbase: '._xcrudDetail', defaultValue: field?undefined:{}})
    },
    setXCrudDetail(field, value, reset) {
      if(!field&&!reset) value = {...this.getXCrudDetail(), ...value}
      this.setXData(field, value, this.xcrudDataPathDetail)
      return value
    },

    /**
     * crud 父内容数据
     */
    getXCrudParent() {
      return this.getXData('', {xbase: '._xcrudParent'})
    },
    setXCrudParent(value) {
      this.setXData(this.xcrudDataPathParent, value, '')
      return value
    },
    /**
     * crud 详情 id 数据
     */
    getXCrudId() {
      return this.getXData(this.xcrudDataPathId, '')
    },
    setXCrudId(value) {
      this.setXData(this.xcrudDataPathId, value, '')
      return value
    },

    
    /**
     * 为网络请求组织父级的数据
     */
    getParentData(type, params, data) {
      if(this.emitHostXCallBack('xcrud.onBeforePayloadParentData'+type, type, params, data, this)) return
      let xcrudParent = this.getXCrudParent()
      if(xcrudParent) params[this.getXMeta('parrentKey', 'id')] = xcrudParent
      this.emitHostXCallBack('xcrud.onPayloadParentData'+type, type, params, data, this)
    },
    /**
     * 为网络请求组织查询过滤的数据
     */
    getQueryData(type, params, data) {
      if(this.emitHostXCallBack('xcrud.onBeforePayloadQueryData'+type, type, params, data, this)) return
      if(type==='list') Object.assign(data, this.getXCrudQuery())
      this.emitHostXCallBack('xcrud.onPayloadQueryData'+type, type, params, data, this)
    },
    /**
     * 为网络请求组织查询分页的数据
     */
    getPagingData(type, params, data) {
      if(this.emitHostXCallBack('xcrud.onBeforePayloadPagingData'+type, type, params, data, this)) return
      if(type==='list'){
        let paging = this.getXCrudPaging()
        data.pageIndex = paging.pageIndex
        data.pageSize = paging.pageSize
      }
      this.emitHostXCallBack('xcrud.onPayloadPagingData'+type, type, params, data, this)
    },
    /**
     * 为网络请求组织新增，修改，通用提交的数据
     */
    getSubmitDataWithRule(type, params, data, item) {
      if(this.emitHostXCallBack('xcrud.onBeforePayloadSubmitData'+type, type, params, data, this, item)) return
      
      if(type==='Create'||type==='Update'||type==='Submit') {
        if(this.xfields) {
          for(let meta of this.xfields) {
            let xdata = this.getXCrudDetail()

            let xif = this.getXMeta('xif', undefined, {xdata, xbase: meta})
            let xcode = this.getXMeta('xcode', undefined, {xdata, xbase: meta})
            if(xif===false||xcode==='None') continue

            let xtitle = this.getXMeta('xtitle', undefined, {xdata, xbase: meta}) 
            let xfield = this.getXMeta('xfield', undefined, {xdata, xbase: meta})

            let dvalue = this.getXCrudDetail(xfield)
            let xvalue = this.getXMeta('xvalue', undefined, {xdata, xbase: meta, extra: dvalue})
            dvalue = xvalue || dvalue
            let xrule = this.getXMeta('xrule', undefined, {xdata, xbase: meta, isRaw: true})
            let xruleMessage = this.getXMeta('xruleMessage', undefined, {xdata, xbase: meta}) 
            let xsubmit = this.getXMeta('xsubmit', undefined, {xdata, xbase: meta, isRaw: true})

            let xruleMessageExtra = '不能为空'
            if(xrule===true) {
              let xrule0 = this.getXMeta('xrule0', undefined, {xdata, xbase: meta})
              xrule = (xmeta, xdata, x, value)=>Boolean(value||(value===0&&xrule0))
            }else if(xrule==='number') {
              xrule = (xmeta, xdata, x, value)=>!isNaN(value)
              xruleMessageExtra = '需要是有效数字'
            }
            if(xrule&&!xrule(meta, xdata, this, dvalue)) {
              let message = xruleMessage||`${xtitle}${xruleMessageExtra}`
              throw new Error(message)
            }
  
            if(xsubmit===false) {
              continue
            }else if(typeof xsubmit==='function') {
              let ret = xsubmit(meta, xdata, this, dvalue)
              Object.assign(data, ret)
            }else{
              data[xfield] = dvalue
            }
          }
        }else{
          Object.assign(data, this.getXCrudDetail())
        }
        
        if(type==='Create') {
          let xcrudParent = this.getXCrudParent()
          if(xcrudParent) data[this.getXMeta('primaryKey', 'parentId', {xbase: 'xcrud'})] = xcrudParent
        }
      }else if(type==='Delete') {
        Object.assign(data, item)
      }

      this.emitHostXCallBack('xcrud.onPayloadSubmitData'+type, type, params, data, this, item)
    },
    /**
     * 网络请求
     */
    doNetwork(type, p) {
      this.debug('doNetwork', type, p)
      let payload = {
        url: this.getXMeta('url'+type, {xbase: 'xcrud'}),
        params: {},
        data: {},
        method: this.getXMeta('method'+type, {xbase: 'xcrud', defaultValue: (type==='list'||type==='detail')?'GET':'POST'})
      }

      try {
        this.getParentData(type, payload.params, payload.data, p)
        this.getQueryData(type, payload.params, payload.data, p)
        this.getPagingData(type, payload.params, payload.data, p)
        this.getSubmitDataWithRule(type, payload.params, payload.data, p)
      }catch(e) {
        this.$notify.showToast(e&&e.message||e||'未知错误')
        return Promise.reject()
      }

      this.debug('doNetwork', payload)
      
      if(this.emitHostXCallBack('xcrud.onBefore'+type, payload, this)) return Promise.resolve()
      if(this.emitHostXCallBack('xcrud.on'+type, payload, this)) return Promise.resolve()
      let ret = this.$x.request(payload).then(res=>{
        let ares = this.emitHostXCallBack('xcrud.onBeforeResonse'+type, res, payload, this)
        if(ares) res = ares
        if(this.emitHostXCallBack('xcrud.onResonse'+type, res, payload, this)) return Promise.resolve(res)

        if(type==='list') {
          let list = []
          if(this.getXMeta('canPaging', {xbase: 'xcrud'})!=false) {
            list = list.concat(res.data.records)
          }else{
            list = list.concat(res.data)
          }
          this.setXCrudList(list)
        } else if(type==='Detail') {
          this.setXCrudDetail(undefined, res.data)
        } else if(type==='Create') {
          this.$notify.showToast('添加成功')
          this.$navigator.navigateBack()
        } else if(type==='Update') {
          this.$notify.showToast('修改成功')
          this.$navigator.navigateBack()
        } else if(type==='Delete'&&this.xcrudType==='list') {
          this.$notify.showToast('删除成功')
          this.refresh()
        }
        
        this.emitHostXCallBack('xcrud.onAfterResonse'+type, res, payload, this)
      })
      if(this.emitHostXCallBack('xcrud.onAfter'+type, payload, this)) return Promise.resolve()

      this.debug('doNetwork', 'exit', ret)
      return ret
    },

    /**
     * 网络请求：新增
     */
    doCreate() {
      return this.doNetwork('create')
    },
    /**
     * 网络请求：查询列表
     */
    doList() {
      return this.doNetwork('list')
    },
    /**
     * 网络请求：查询列表
     */
    doDetail() {
      return this.doNetwork('Detail')
    },
    /**
     * 网络请求：修改
     */
    doUpdate() {
      return this.doNetwork('Update')
    },
    /**
     * 网络请求：删除
     */
    doDelete(p) {
      return this.doNetwork('Delete', p)
    },
    /**
     * 网络请求：通用提交类型
     */
    doSubmit() {
      return this.doNetwork('Submit')
    },
    /**
     * 网络请求：根据 crud type
     */
    doSubmitByType() {
      return this.doNetwork(this.xcrudType)
    },
    
    /**
     * 去新增
     */
    doToCreate() {
      let params = {
        xcrudType: 'Create',
        xcrudParent: this.getXCrudParent()
      }
      if(this.emitHostXCallBack('xcrud.onBeforeToCreate', params)) return
      this.$navigator.navigateTo('/'+getCurrentPages()[this.xid].route, params)
      return this.emitHostXCallBack('xcrud.onToCreate', params)
    },
    /**
     * 去修改
     */
    doToUpdate(p) {
      let params = {
        xcrudType: 'Update',
        xcrudDetail: JSON.stringify(p)
      }
      if(this.emitHostXCallBack('xcrud.onBeforeToUpdate', p, params)) return
      this.$navigator.navigateTo('/'+getCurrentPages()[this.xid].route, params)
      return this.emitHostXCallBack('xcrud.onToUpdate', p, params)
    },
    /**
     * 去子级别列表
     */
    doToSub(p) {
      let params = {
        xcrudType: 'list',
        xcrudParent: p[this.getXMeta('primaryKey', 'id', {xbase: 'xcrud'})]
      }
      if(this.emitHostXCallBack('xcrud.onBeforeToSub', p, params)) return
      this.$navigator.navigateTo('/'+getCurrentPages()[this.xid].route, params)
      return this.emitHostXCallBack('xcrud.onToSub', p, params)
    }
  }
}